package com.cskaoyan.service.wx.lxc;

import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.po.MarketAddress;
import com.cskaoyan.bean.po.MarketAddressExample;
import com.cskaoyan.mapper.MarketAddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WxAddressServicelmpl implements WxAddressService {

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Override
    public CommonData<MarketAddress> queryAddressList() {
        List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(new MarketAddressExample());
        int total = (int) marketAddressMapper.countByExample(new MarketAddressExample());
        return new CommonData<>(total, 1, total, 1, marketAddresses);
    }

    @Override
    public int saveAddress(MarketAddress marketAddress, Integer userId) {
        if (marketAddress.getIsDefault()) {
            MarketAddressExample marketAddressExample = new MarketAddressExample();
            MarketAddressExample.Criteria criteria = marketAddressExample.createCriteria();
            criteria.andIsDefaultEqualTo(true);
            MarketAddress marketAddress1 = new MarketAddress();
            marketAddress1.setIsDefault(false);
            marketAddressMapper.updateByExampleSelective(marketAddress1,marketAddressExample);
        }
        if (marketAddress.getId() != 0) {
            marketAddress.setUpdateTime(new Date());
            int code = marketAddressMapper.updateByPrimaryKeySelective(marketAddress);
            if (code == 0) {
                return 0;
            }
        } else {
            marketAddress.setUserId(userId);
            marketAddress.setAddTime(new Date());
            marketAddress.setUpdateTime(new Date());
            int code = marketAddressMapper.insertSelective(marketAddress);
            if (code == 0) {
                return 0;
            }
        }
        return marketAddress.getId();
    }

    @Override
    public MarketAddress detailAddress(Integer id) {
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(id);
        return marketAddress;
    }

    @Override
    public int deleteAddress(Integer id) {
        int code = marketAddressMapper.deleteByPrimaryKey(id);
        return code;
    }
}
